
6. Content providers
Mobile Applications - 4. Storing data in Android
73
Method to initialize the provider
Method to return the MIME type
corresponding to a content URI
Method to read data from the provider
Method to write data into the provider
Method to delete data from the provider
Method to update data from the
provider
class MyContentProvider : ContentProvider() {
private lateinit var dbHelper: MyDatabaseHelper
override fun onCreate(): Boolean {
dbHelper = MyDatabaseHelper(context!!)
return true
}
override fun query(
uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor {
val db = dbHelper.readableDatabase
return db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder)
}
override fun insert(uri: Uri, values: ContentValues?): Uri {
val db = dbHelper.writableDatabase
val id = db.insert(TABLE_NAME, null, values)
return ContentUris.withAppendedId(uri, id)
}
override fun update(
uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?
): Int {
val db = dbHelper.writableDatabase
return db.update(TABLE_NAME, values, selection, selectionArgs)
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
val db = dbHelper.writableDatabase
return db.delete(TABLE_NAME, selection, selectionArgs)
}
override fun getType(uri: Uri): String {
return "vnd.android.cursor.dir/vnd.com.example.provider.${TABLE_NAME}"
}
}